import numpy
from matplotlib import pyplot

#data=numpy.loadtxt('./testSet.txt',delimiter='\t',encoding='utf-8')
def line(w,b,x):
    return (-b-w[0]*x)/w[1]
def sigmoid(x):
    return 1/(1+numpy.exp(-x))
def regression(data,w,b,alpha,y,epoch):
    length=len(y)
    for i in range(epoch):
        temp = (sigmoid(numpy.dot(data,w)+b) - y) * sigmoid(numpy.dot(data,w)+b) *\
                (1 - sigmoid(numpy.dot(data,w)+b))
        w_delta=numpy.dot(temp,data)
        b_delta=numpy.sum(temp)
        w=w-alpha*w_delta
        b=b-alpha*b_delta
        res=sigmoid(numpy.dot(data,w)+b)
        res=numpy.where(res<0.5,0,1)
        percent=numpy.sum(res==y)/length
        print(percent,w_delta[0])
    return  w,b
def load_data(seed=2020264):  # 🍕🍕🍕生成数据集🍕🍕🍕
    numpy.random.seed(seed)  # 设置随机数种子
    N = 100  # 各类的样本数
    DIM = 2  # 数据的元素个数
    CLS_NUM = 2  # 类别数

    x = numpy.zeros((N * CLS_NUM, DIM))
    t = numpy.zeros((N * CLS_NUM, CLS_NUM), dtype=int)

    for j in range(CLS_NUM):
        for i in range(N):  # N*j, N*(j+1)):
            rate = i / N
            radius = 1.0 * rate
            theta = j * 4.0 + 4.0 * rate + numpy.random.randn() * 0.2

            ix = N * j + i
            x[ix] = numpy.array([radius * numpy.sin(theta),
                              radius * numpy.cos(theta)]).flatten()
            t[ix, j] = 1

    return x, t
feature, label = load_data()
label=numpy.argmax(label,axis=1)
data=numpy.hstack((feature,label.reshape((-1,1))))
pyplot.scatter(feature[:,0],feature[:,1],c=label)
pyplot.show()
shape=data.shape
w=numpy.random.randn(shape[1]-1)
b=numpy.random.randn(1)
w,b=regression(data[:,0:-1],w,b,0.01,data[:,-1],10000)
pyplot.scatter(data[:,0],data[:,1],c=data[:,2])
pyplot.plot(list(range(-3,4)),line(w,b,numpy.array(list(range(-3,4)))))
pyplot.xlim([-1,1])
pyplot.show()